package com.scut.edu.wanyou;


import com.weibo.android.sdk.util.Utility;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthError;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SinaOAuthActivity extends Activity {

	private static final String TAG = "OAuthAuthorizeWebView";
	
	public static String URL_OAUTH2_ACCESS_AUTHORIZE = "https://open.weibo.cn/oauth2/authorize";
	
	public static final int OAUTH_RESULT_CODE = 1;
	
	private String auth_url = null;
	
	private ProgressDialog progress = null;
	
	private WebView webView = null;
	
	private Weibo weibo = null;

	public Oauth2AccessToken accessToken = null;
	
	public static final String KEY_TOKEN = "access_token";
	public static final String KEY_EXPIRES = "expires_in";
	public static final String KEY_REFRESHTOKEN = "refresh_token";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sina_oauth);
		
		weibo = Weibo.getInstance();
		
		auth_url = weibo.getOAuthURL();
		Log.i(TAG, auth_url);
		
		progress = new ProgressDialog(this);
		progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
		progress.setMessage("正在加载新浪授权页...");
		progress.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				onBack();
				return false;
			}
		});
		
		webView = (WebView)findViewById(R.id.sina_oauth_webview);
		
        setUpWebView();
	}
	
	protected void onBack() {
		try {
			progress.dismiss();
			if (null != webView) {
				webView.stopLoading();
				webView.destroy();
			}
		} catch (Exception e) {
		}
		finish();
	}
	
	private Handler handler = new Handler();
	
	private void setUpWebView()
	{
		WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webView.requestFocus();
        webView.setWebViewClient(new WeiboWebViewClient());
        webView.loadUrl(auth_url);
        Log.i(TAG, "webView loading");
	}
	
	private class WeiboWebViewClient extends WebViewClient
	{

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			if(progress.isShowing())
				progress.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onPageStarted URL: " + url);
			if (url.startsWith(weibo.getRedirecturl())) {
				handleRedirectUrl(view, url);
				view.destroyDrawingCache();
                view.destroy();
			}
			progress.show();
			super.onPageStarted(view, url, favicon);
		}
		
	}
	
	private void handleRedirectUrl(WebView view, String url) {
		Bundle values = Utility.parseUrl(url);

		String error = values.getString("error");
		String error_code = values.getString("error_code");

		if (error == null && error_code == null) {
			listener.onComplete(values);
		} else if (error.equals("access_denied")) {
			// 用户或授权服务器拒绝授予数据访问权限
			listener.onCancel();
		} else {
			if(error_code==null){
				listener.onWeiboException(new WeiboException(error, 0));
			}
			else{
				listener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
			}
			
		}
	}
	
	private WeiboAuthListener listener = new  WeiboAuthListener(){
		
		@Override
		public void onComplete(Bundle values) {
			
			if (null == accessToken) {
				accessToken = new Oauth2AccessToken();
			}
			
			accessToken.setToken(values.getString(KEY_TOKEN));
			accessToken.setExpiresIn(values.getString(KEY_EXPIRES));
			accessToken.setRefreshToken(values.getString(KEY_REFRESHTOKEN));
			
			if (accessToken.isSessionValid()) {
				Log.i(TAG, "success");
				Intent intent = new Intent();
				intent.putExtra("accessToken", accessToken);
				setResult(OAUTH_RESULT_CODE, intent);
				SinaOAuthActivity.this.finish();
			} else {
				Log.d("Weibo-authorize", "Failed to receive access token");
			}
		}

		@Override
		public void onError(WeiboAuthError error) {
			Log.d("Weibo-authorize", "Login failed: " + error);
		}

		@Override
		public void onWeiboException(WeiboException error) {
			Log.d("Weibo-authorize", "Login failed: " + error);
		}

		@Override
		public void onCancel() {
			Log.d("Weibo-authorize", "Login canceled");
		}
	};
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		destroy();
		super.onDestroy();
	}
	
	private void destroy()
	{
		if(progress.isShowing())
			progress.dismiss();
		if(webView!=null){
		    CookieSyncManager.createInstance(this);   
		    CookieManager cookieManager = CookieManager.getInstance();  
		    cookieManager.removeAllCookie();  
			webView.destroyDrawingCache();
			webView.destroy();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			destroy();
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

}
